<?php
namespace Rainrock\Framework\kernel\base;



class Jiami{
	
	private static $keystr = 'abcdefghijklmnopqrstuvwxyz';
	private static $jmsstr = '';
	
	/**
	*	随机rand
	*/
	public static function getRandkey()
	{
		return str_shuffle(self::$keystr);
	}
	
	/**
	*	base64加密
	*/
	public static function base64encode($str)
	{
		if(!$str)return '';
		$str	= base64_encode($str);
		$str	= str_replace(array('+', '/', '='), array('!', '.', ':'), $str);
		return $str;
	}
	
	/**
	*	base64解密
	*/
	public static function base64decode($str)
	{
		if(!$str)return '';
		$str	= str_replace(array('!', '.', ':'), array('+', '/', '='), $str);
		$str	= base64_decode($str);
		return $str;
	}
	
	/**
	*	获取随机的md5
	*/
	public static function getRandmd5()
	{
		$str = time().self::getRandkey().rand(1000,9999);
		return md5($str);
	}
	
	private static function getjmkey()
	{
		if(!self::$jmsstr)self::$jmsstr = Base::getConfig('randkey');
		return self::$jmsstr;
	}
	
	
	/**
	*	加密
	*/
	public static function encrypt($str)
	{
		$s	= self::base64encode($str);
		$s	= self::encrypts($s);
		return $s;
	}

	/**
	*	解密
	*/
	public static function uncrypt($str)
	{
		$s	= self::uncrypts($str);
		$s	= self::base64decode($s);
		return $s;
	}
	
	
	private static function encrypts($str, $a='')
	{
		if($a=='')$a = self::getjmkey();
		$nstr	= '';
		if(Rock::isempt($str))return $nstr;
		$len	= strlen($str);
		$t		= rand(1, 14);
		if($t == 10)$t++;
		for($i=0; $i<$len; $i++){
			$nstr.='0';
			$sta	= substr($str,$i,1);
			$orstr	= ''.ord($sta).'';
			$ile	= strlen($orstr);
			for($j=0; $j<$ile; $j++){
				$oi	= (int)substr($orstr,$j,1)+$t;
				$nstr.= substr($a,$oi,1);
			}
		}
		if($nstr != ''){
			$nstr = substr($nstr,1);
			$nstr.= '0'.$t.'';
		}	
		return $nstr;
	}
	
	private static function uncrypts($str, $a1='')
	{
		$nstr	= '';
		if(Rock::isempt($str))return $nstr;
		if($a1=='')$a1	= self::getjmkey();
		$a	= array();
		for($i=0; $i<strlen($a1); $i++)$a[substr($a1, $i, 1)] = ''.$i.'';
		$na	= explode('0', $str);
		$len= count($na);
		$r	= (int)$na[$len-1];
		for($i=0; $i<$len-1; $i++){
			$st	= $na[$i];
			$sl = strlen($st);
			$sa	= '';
			for($j=0; $j<$sl; $j++){
				$ha	= substr($st,$j,1);
				if(isset($a[$ha]))$ha = $a[$ha] - $r;
				$sa.=$ha;
			}
			$sa	= (int)$sa;
			$nstr.=chr($sa);
		}
		return $nstr;
	}
}